<?php
require __DIR__ . '/file_storage.php';

$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
function anonymize_ip($ip) {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $parts = explode('.', $ip);
        $parts[3] = '0';
        return implode('.', $parts);
    }
    return $ip;
}

$ip_store = anonymize_ip($ip);

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$ref = $_SERVER['HTTP_REFERER'] ?? '';
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

$consent = isset($_REQUEST['consent']) && $_REQUEST['consent'] == '1';
$ua_hash = hash('sha256', 'salt|' . $ua);
$ref_hash = $ref ? hash('sha256', 'salt|' . $ref) : null;
$ua_raw = $consent ? $ua : null;

// 获取GPS数据
$gps_lat = $gps_lng = $gps_acc = null;
if ($method === 'POST') {
    $rawData = file_get_contents('php://input');
    if ($rawData) {
        $jsonData = json_decode($rawData, true);
        if ($jsonData && isset($jsonData['gps']) && $jsonData['gps']) {
            $gpsData = $jsonData['gps'];
            $gps_lat = isset($gpsData['lat']) ? round($gpsData['lat'], 6) : null;
            $gps_lng = isset($gpsData['lng']) ? round($gpsData['lng'], 6) : null;
            $gps_acc = isset($gpsData['accuracy']) ? (int)$gpsData['accuracy'] : null;
        }
    }
}

save_log([
    'ip' => $ip_store,
    'ua_hash' => $ua_hash,
    'ua_raw' => $ua_raw,
    'ref_hash' => $ref_hash,
    'path' => $path,
    'method' => $method,
    'lang' => $lang,
    'consent' => $consent ? 1 : 0,
    'gps_lat' => $gps_lat,
    'gps_lng' => $gps_lng,
    'gps_acc' => $gps_acc
]);

// 返回 204
http_response_code(204);
header('Cache-Control: no-store');